package net.yyge.manifest.xml2axml;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;


public class AxmlUtils {


    public static String decode(byte[] data) {
        try (InputStream is = new ByteArrayInputStream(data);
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {

            PrintStream printStream = new PrintStream(os, false, "UTF-8");
            AXMLPrinter.out = printStream;

            AXMLPrinter.decode(is);

            // 获取输出内容
            byte[] resultBytes = os.toByteArray();
            return new String(resultBytes, "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String decode(File file) throws IOException {
        byte[] data = readFileToByteArray(file);
        return decode(data);
    }


    public static byte[] encode(String xml) {
        try {
            Encoder encoder = new Encoder();
            return encoder.encodeString(null, xml);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] encode(File file) {
        try {
            Encoder encoder = new Encoder();
            return encoder.encodeFile(null, file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private static byte[] readFileToByteArray(File file) throws IOException {
        Path path = file.toPath();
        return Files.readAllBytes(path);
    }
    /*
    private static byte[] readFileToByteArray(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[8192];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        }
    }
    */
}